<template>
	<div class="gd-map-wraper">

		<a-spin v-show="initMapLoading" :spinning="initMapLoading" tip="地图数据处理中，请稍候..." />

		<div ref="gdMap" class="gd-map-container" id="a-map" />

	</div>
</template>

<script>

import { GdMap } from "@/utils/gdMap";
import AMapLoader from '@amap/amap-jsapi-loader';

export default {
	name: "mapcomponents",
	props: {
		markers: { // 点 改变数组长度会生效
			type: Array,
			default: () => []
		},

		largeMarkers: { // 海量点 改变数组长度会生效
			type: Array,
			default: () => []
		},

		clusterMarker: { // 聚合点 改变数组长度会生效
			type: Array,
			default: () => []
		},

		polygonPath: { // 不规则图形 改变数组长度会生效
			type: Array,
			default: () => []
		},
		pageState: {
			type: Object,
			default: () => ({}),
		}
	},

	watch: {
		'markers.length': {
			handler(newVal, oldVal) {
				this.addMarker();
			}
		},

		'largeMarkers.length': {
			handler(newVal, oldVal) {
				this.addLargeMarker();
			}
		},

		'clusterMarker.length': {
			handler(newVal, oldVal) {
				if (this.pageState.hotType == 1) {
					this.drawHeatMap()
				} else {
					this.addClusterMarker();
				}
			}
		},

		'polygonPath': {
			handler(newVal, oldVal) {
				this.addPolyPath();
			},
			deep: true
		},
	},

	data() {
		return {
			initMapLoading: true,
			map: null,
			polygons: [],
		};
	},

	async created() {
		await this.initMap();
	},

	destroyed() {
		this.map = null;
	},

	methods: {

		async addMarker(lat, lng, icon) {
			if (!window.AMap) {
				await this.initMap();
			}
			const arr = [];
			this.markers.map(item => {
				const marker = new window.AMap.Marker({
					position: new window.AMap.LngLat(item[0], item[1]),
					icon: icon || '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
					offset: new window.AMap.Pixel(-13, -30),
				});
				arr.push(marker)
			})
			this.map.add(arr)
		},

		addLargeMarker() {
			const icon = {
				type: 'image', // 图标类型，现阶段只支持 image 类型
				image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png', // 图片 url
				size: [6, 9],
				anchor: 'bottom-center',
			};
			const labelMarkers = []
			this.largeMarkers.map(item => {
				var LabelMarker = new window.AMap.LabelMarker({
					position: item,//[116.466994, 39.984904], //
					zIndex: 16,
					icon: icon, // 将第一步创建的 icon 对象传给 icon 属性
				})
				labelMarkers.push(LabelMarker)
			})

			const labelsLayer = new window.AMap.LabelsLayer({
				zooms: [3, 20],
				zIndex: 1000,
				collision: true,  // 该层内标注是否避让
				allowCollision: true, // 设置 allowCollision：true，可以让标注避让用户的标注
			});

			// 添加一个 labelMarker
			labelsLayer.add(labelMarkers);
			this.map.add(labelsLayer);
			this.map.setFitView()
		},

		async addClusterMarker() {
			if (!window.AMap) {
				await this.initMap();
				this.addClusterMarker();
			}

			this.clearHearPoint();
			this.clearClusterMarker();

			var points = [];
			var gridSize = 60;

			this.clusterMarker.map(i => {
				points.push({ lnglat: i })
			})

			var count = points.length;

			var _renderClusterMarker = function (context) {
				var factor = Math.pow(context.count / count, 1 / 18);
				var div = document.createElement('div');
				var Hue = 180 - factor * 180;
				//Hue:  0, 60, 120, 180, 240, 300, 360
				var bgColor = 'hsla(' + Hue + ',100%,40%,0.7)';
				var fontColor = 'hsla(' + Hue + ',100%,90%,1)';
				var borderColor = 'hsla(' + Hue + ',100%,40%,1)';
				var shadowColor = 'hsla(' + Hue + ',100%,90%,1)';
				div.style.backgroundColor = bgColor;
				var size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
				div.style.width = div.style.height = size + 'px';
				div.style.border = 'solid 1px ' + borderColor;
				div.style.borderRadius = size / 2 + 'px';
				div.style.boxShadow = '0 0 5px ' + shadowColor;
				div.innerHTML = context.count;
				div.style.lineHeight = size + 'px';
				div.style.color = fontColor;
				div.style.fontSize = '14px';
				div.style.textAlign = 'center';
				context.marker.setOffset(new window.AMap.Pixel(-size / 2, -size / 2));
				context.marker.setContent(div)
			};
			var _renderMarker = function (context) {
				var content = '<div style="background-color: hsla(180, 100%, 50%, 0.3); height: 18px; width: 18px; border: 1px solid hsl(180, 100%, 40%); border-radius: 12px; box-shadow: hsl(180, 100%, 50%) 0px 0px 3px;"></div>';
				var offset = new window.AMap.Pixel(-9, -9);
				context.marker.setContent(content)
				context.marker.setOffset(offset)
			}

			this.map.plugin(["AMap.MarkerClusterer"], () => {
				this.clusterInstance = new window.AMap.MarkerClusterer(
					this.map,
					points,
					{
						gridSize: gridSize, // 设置网格像素大小
						renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
						renderMarker: _renderMarker, // 自定义非聚合点样式
					}
				);
				if (this.clusterMarker && this.clusterMarker.length) {
					this.setMapCenter(this.clusterMarker[0]);
				}
				// this.map.setFitView(); // 跨省之后, 不太好用
			});
		},

		// 设置地图中心
		setMapCenter(center) {
			if (this.map) {
				this.map.setCenter(center);
			}
		},

		// 设置地图缩放层级
		setMapZoom(level) {
			if (this.map) {
				this.map.setZoom(level);
			}
		},

		async addPolyPath() {
			this.clearPolygons();
			if (!window.AMap) {
				await this.initMap();
				this.addPolyPath();
			}
			this.polygonPath.forEach((item, index) => {

				// 创建面覆盖物
				let polygon = new window.AMap.Polygon({
					path: item.path, // [...item.aoi_edge, ...item.poi_edge],
					strokeWeight: 1,
					fillOpacity: 0.6,
					fillColor: '#FB4C2C',
					strokeStyle: 'dashed',
					strokeColor: '#93A7D5',
					// strokeDasharray: [5, 5],
					extData: {
						uuid: item.uuid,
						aoi_id: item.aoi_id,
					},
					zIndex: 100,
					cursor: 'pointer'
				});
				polygon.on('click', (e) => {
					this.pageState.uuid = e.target._opts.extData.uuid;
					this.showColorModal();
				})
				this.polygons.push(polygon);
				this.map.add(polygon)
			})
		},

		// 设置多边形选中状态
		setSelected(polygon) {
			if (this.activePolygon) {
				this.map.remove(this.activePolygon);
			}

			if (polygon && polygon.path && polygon.path.length) {
				this.activePolygon = new window.AMap.Polygon({
					path: polygon.path,
					strokeWeight: 2,
					strokeColor: "blue",
					fillColor: "blue",
				});
				this.map.add(this.activePolygon);
			}

		},

		// 清除多边形
		clearPolygons() {
			if (Array.isArray(this.polygons) && this.polygons.length && this.map) {
				this.map.remove(this.polygons);
			}
		},

		// 清除聚合点
		clearClusterMarker() {
			if (this.clusterInstance) {
				this.clusterInstance.setData([]);
			}
		},

		// 清除热力图
		clearHearPoint() {
			if (this.heatmap) {
				this.heatmap.setDataSet({
					data: [],
				})
			}
		},

		drawHeatMap() {
			this.clearClusterMarker();
			this.clearHearPoint();

			const points = [];
			this.clusterMarker.map(i => {
				points.push({
					"lng": i[0],
					"lat": i[1],
					"count": 10 // TODO: 因为数据的关系, 热力值设置为 10
				})
			})

			if (this.heatmap) {
				this.heatmap.setDataSet({
					data: points,
					max: 100
				});
				if (this.clusterMarker && this.clusterMarker.length) {
					this.setMapCenter(this.clusterMarker[0]);
				}
				return;
			}

			this.map.plugin(["AMap.HeatMap"], () => {
				this.heatmap = new AMap.HeatMap(this.map, {
					radius: 25,
					opacity: [0, 0.8]
				});
				this.heatmap.setDataSet({
					data: points,
					max: 100
				});
				if (this.clusterMarker && this.clusterMarker.length) {
					this.setMapCenter(this.clusterMarker[0]);
				}
			});
		},

		judePluginExit(pluginName) {
			return window.AMap.plugin.isLoaded(pluginName)
		},

		async initMap() {
			try {

				AMapLoader.reset()
				const params = {
					key: "92e730d580645f58e1c84d2109066e53",
					version: "2.0"
				};
				await AMapLoader.load(params)

				this.map = new GdMap(this.$refs.gdMap);
				this.map.on("complete", () => {
					this.initMapLoading = false;
				});
			} catch (e) {
				// this.clearPolygonByPolygonList();
				this.$message.warning("高德地图初始化失败，请刷新重试");
			}
		},

		showColorModal(id) {
			this.$emit('showBusinessModal', id)
		},

		setCenter(gis) {
			if (!this.map) {
				this.$message.error("请先初始化地图")
				return
			}
			this.map.setCenter(gis)
		},
	},
};
</script>

<style lang="less" scoped>
.gd-map-wraper {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 800px;
	position: relative;
	background-color: #fff;
	padding: 20px;
	border-radius: 4px;
	margin-bottom: 16px;
	padding-bottom: 0;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.gd-map-container {
	width: 100%;
	height: 760px;
}

.ant-spin {
	position: absolute;
	top: 0;
	left: 0;
	z-index: 100;
	background: #ffffff54;
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	flex-wrap: wrap;
}
</style>
